//
//  ConvertViewController.swift
//  worldexchange
//
//  Created by xionghao on 2019/2/12.
//  Copyright © 2019 xionghao. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import InputKit


class ConvertViewController: QMUICommonViewController, QMUIModalPresentationContentViewControllerProtocol, QMUITextFieldDelegate {
    @IBOutlet weak var changeShopWrapper: UIView!
    @IBOutlet weak var currencyWrapper: UIView!
    @IBOutlet weak var rateLabel: UILabel!

    @IBOutlet weak var sellButton: UIButton!
    @IBOutlet weak var inputWrapper: UIView!
    @IBOutlet weak var buyButton: UIButton!
    @IBOutlet weak var currentCrencyLabel: UILabel!
    @IBOutlet weak var shopNameLabel: UILabel!

    @IBOutlet weak var titleLabel: UILabel!
    var isBuying = true

    @IBOutlet weak var btnAppoinment: QMUIFillButton!
    @IBOutlet weak var fromLabel: UILabel!

    @IBOutlet weak var toLabel: UILabel!
    var chooseMoneyItem: MoneyItem?
    let disposeBag = DisposeBag()

    @IBOutlet weak var moneyTF: TXLimitedTextField!

    @IBAction func appointClick(_ sender: QMUIButton) {
        if !isLogin {
            Utils.pushLogin()
        }else {
            let rate = chooseMoneyItem!.rates[0]
            let apVc = SubmitOrderViewController()
            rate.money = chooseMoneyItem!
            apVc.rate = rate
            apVc.money = Double(self.moneyTF.text!) ?? 0.00
            apVc.isBuying = isBuying
            
            
            
            self.parent?.dismiss(animated: true, completion: {
                let root = UIApplication.shared.delegate?.window??.rootViewController
                let vc = root as? AppTabBarViewController
                
               let nav = vc?.selectedViewController as? AppNavViewController
                nav?.pushViewController(apVc, animated: true)
            })
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupView()
        refreshView()
        NotificationCenter.default.addObserver(self, selector: #selector(refreshView), name: NSNotification.Name.init(rawValue: appMoneyLoadEndNoticeName), object: nil)
        //        NotificationCenter.default.addObserver(self, selector: #selector(receiveShopChange), name: NSNotification.Name.init(rawValue: changeShopNoticeName), object: nil)
        //        NotificationCenter.default.addObserver(self, selector: #selector(receiveCurrencyChange), name: NSNotification.Name.init(rawValue: changeCurrencyNoticeName), object: nil)
        // Do any additional setup after loading the view.
    }

    @IBAction func changeButtonClick(_ sender: UIButton) {
        self.isBuying = sender.tag == 0
        self.refreshView()
    }

    @objc func changeMoneyClick(){
        if appMoneyItems.count == 0 {
            QMUITips.show(withText: LanguageHelper.getString(key: "please choose other branches"))
            return
        }
        let contentVc = ChooseCurrencyViewController()
        let modalVc = QMUIModalPresentationViewController()
        modalVc.contentViewController = contentVc
        modalVc.animationStyle = .slide
        contentVc.cancelBlock = {
            modalVc.dismiss(animated: true)
        }
        contentVc.selectBlock = {
            item in
            print(item)
            modalVc.dismiss(animated: true) {
                self.chooseMoneyItem = item
                self.refreshView()
            }
        }
       

        self.present(modalVc, animated: true)

    }

//    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//        let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
//
//        let expression = "^[0-9]*((\\\\.|,)[0-9]{0,2})?$"
//        let regex = try! NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.allowCommentsAndWhitespace)
//        let numberOfMatches = regex.numberOfMatches(in: newString, options:NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (newString as NSString).length))
//        return numberOfMatches != 0
//    }


    func setupView() {
        //        self.changeShopWrapper.layer.cornerRadius = 5
        self.changeShopWrapper.layer.borderWidth = 0.5
        self.changeShopWrapper.layer.borderColor = UIColor.qmui_color(withHexString: "#222222")?.cgColor
        self.changeShopWrapper.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(changeShopClick))
        self.changeShopWrapper.addGestureRecognizer(tap)
        //        self.currencyWrapper.layer.cornerRadius = 5
        self.currencyWrapper.layer.borderWidth = 0.5
        self.currencyWrapper.layer.borderColor = UIColor.qmui_color(withHexString: "#222222")?.cgColor

        let tap2 = UITapGestureRecognizer(target: self, action: #selector(changeMoneyClick))
        self.currencyWrapper.addGestureRecognizer(tap2)
        self.currencyWrapper.isUserInteractionEnabled = true

        //        self.inputWrapper.layer.cornerRadius = 5
        self.inputWrapper.layer.borderWidth = 0.5
        self.inputWrapper.layer.borderColor = UIColor.qmui_color(withHexString: "#222222")?.cgColor
        self.btnAppoinment.setTitle("预约".localized(), for: UIControl.State.normal)
        self.btnAppoinment.cornerRadius = 0
        self.btnAppoinment.isHidden = true
        self.moneyTF.limitedType = .price
        // this means, that only five ints can be inputted
        moneyTF.limitedPrefix = 10
        // this means, that only five decimal can be inputted
        moneyTF.limitedSuffix = 2
        self.moneyTF.delegate = self
        self.moneyTF.rx.text
                .subscribe(onNext: { [weak self] (value) in
                    self?.refreshMoney()

                }, onError: { (error) in
                }, onCompleted: nil, onDisposed: nil)
                .disposed(by: disposeBag)

    }

    @objc func changeShopClick() {
        let window = UIApplication.shared.delegate?.window
        let tabVc = window??.rootViewController as? AppTabBarViewController
        tabVc?.showChangeShop()
    }

    func refreshMoney() {
        let toUnit = isBuying ? defaultCurrency : chooseMoneyItem?.ex_title ?? ""
        let moneyValue = self.moneyTF.text ?? ""
        var money = 0.00
        if moneyValue == "" {
            money = 0.00
        } else {
            money = Double(moneyValue) ?? 0.00
        }
        var toValue = "0.00 \(toUnit)"
        if chooseMoneyItem != nil {
            let rate = chooseMoneyItem!.rates[0]
            let buying = Double(rate.buying)!
            let selling = Double(rate.selling)!
            let total = isBuying ? buying * money : money / selling
            toValue = String(format: "%.4f \(toUnit)", total)
            if(total == 0){
                self.btnAppoinment.isHidden = true
            }else {
                self.btnAppoinment.isHidden = false
            }
        }else {
            self.btnAppoinment.isHidden = true
        }
        self.toLabel.text = toValue
    }


    @objc func refreshView() {
        if chooseMoneyItem == nil && appMoneyItems.count > 0 {
            chooseMoneyItem = appMoneyItems[0]
        } else if appMoneyItems.count == 0 {
            chooseMoneyItem = nil
        }

        var rateText = ""

        if chooseMoneyItem != nil {
            let rate = chooseMoneyItem!.rates[0]
            
            rateText = isBuying ? "1 \(chooseMoneyItem!.ex_title) = \(rate.buying) \(defaultCurrency)" : "\(rate.selling) \(defaultCurrency) = 1 \(chooseMoneyItem!.ex_title)"
        }
        self.rateLabel.text = rateText
        self.currentCrencyLabel.text = chooseMoneyItem?.ex_title
        self.shopNameLabel.text = currentShop?.title
        self.fromLabel.text = isBuying ? chooseMoneyItem?.ex_title : defaultCurrency
        self.titleLabel.text = LanguageHelper.getString(key: "converterLabel")

        

        let selectedColor = UIColor.qmui_color(withHexString: "#231815")
        let unSelectedColor = UIColor.qmui_color(withHexString: "#e0e0e0")
        let selectedTitleColor = UIColor.white
        let unSelectedTitlleColor = UIColor.qmui_color(withHexString: "#231815")


        self.buyButton.backgroundColor = isBuying ? selectedColor : unSelectedColor
        let buyTitleColor = isBuying ? selectedTitleColor : unSelectedTitlleColor
        self.buyButton.setTitleColor(buyTitleColor!, for: .normal)
        self.buyButton.setTitle(LanguageHelper.getString(key: "buyRateBtnLabel"), for: .normal)


        self.sellButton.backgroundColor = isBuying ? unSelectedColor : selectedColor
        let sellTitleColor = isBuying ? unSelectedTitlleColor : selectedTitleColor
        self.sellButton.setTitleColor(sellTitleColor!, for: .normal)
        self.sellButton.setTitle(LanguageHelper.getString(key: "sellRateBtnLabel"), for: .normal)

        refreshMoney()

    }


    func preferredContentSize(in controller: QMUIModalPresentationViewController!, keyboardHeight: CGFloat, limitSize: CGSize) -> CGSize {
        let contentWidth = (UIScreen.main.bounds.width - 48)
        return CGSize(width: contentWidth, height: 350)
    }


    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */

}
